/**
 *  \file   relay_concurrent_tab.c
 *  \brief  mémorisation des concurrent aux relais durant la période de réception de ACK, choix du meilleur relais au routage et détermination de la position actuelle du noeud en fonction de celle des voisins
 *  \author Miora ANDRIAMANOHARISOA, Loic MINGHETTI
 *  \date   PFE 2011
 **/

#include "include.h"

#define NB_CONCURRENT_MAX 5
concurrent tab_concurrent[NB_CONCURRENT_MAX];

void tab_concurrent_init(void) {
  int i;
  i=0;
  for(i=0; i<NB_CONCURRENT_MAX; i++){
    tab_concurrent[i].node_id = BROADCAST;
    tab_concurrent[i].hop_count = 0;
    tab_concurrent[i].link_quality = 0;
  }
}

/* retourne 0 si crnt est une valeur par défaut sinon 1 */
int concurrent_is_init(concurrent crnt) {
  if ((crnt.node_id == BROADCAST) && (crnt.hop_count == 0) && (crnt.link_quality == 0)) {
    return 0;
  } else {
    return 1;
  }
}

void affiche_tab_concurrent(void) {
  int i;
  i=0;
  printf("\r\n****** TAB_CONCURRENT *********\r\n");
  for(i=0; i<NB_CONCURRENT_MAX; i++){
    if (concurrent_is_init(tab_concurrent[i]) == 1) {
      printf("tab_concurrent[%d] : node_ID = %d, hop_count = %d, link_quality = %d\r\n", i, tab_concurrent[i].node_id, tab_concurrent[i].hop_count, tab_concurrent[i].link_quality);
    }
  }
  printf("\r\n");
}

void add_concurrent(int node_id, int hop_count, int rssi)  {
	int i;
	for (i = NB_CONCURRENT_MAX - 1; i > 0; i--) {
	  tab_concurrent[i] = tab_concurrent[i - 1];
	}
	tab_concurrent[0].node_id = node_id;
	tab_concurrent[0].link_quality = rssi;
	tab_concurrent[0].hop_count = hop_count;
} 

int choose_relay(void){
  int i; 
  concurrent relay;
  i=0;
  relay = tab_concurrent[0];
  for (i=1; i<NB_CONCURRENT_MAX; i++) {
    if ( (tab_concurrent[i].hop_count < relay.hop_count) && (concurrent_is_init(tab_concurrent[i]) == 1)) {
      relay = tab_concurrent[i];
    } else if ((tab_concurrent[i].hop_count == relay.hop_count) && (concurrent_is_init(tab_concurrent[i]) == 1)) {
      if ((tab_concurrent[i].link_quality > relay.link_quality) && (concurrent_is_init(tab_concurrent[i]) == 1)) {
	relay = tab_concurrent[i];
      }
    }
  }
  return relay.node_id;
}

static int min_hop_count_candidate;

void determine_hop_count(void) {
  int i;
  i = 0;
  if (concurrent_is_init(tab_concurrent[0]) == 1) { 
    while (concurrent_is_init(tab_concurrent[i]) == 1) {
      if (tab_concurrent[i].hop_count < min_hop_count_candidate) {
	min_hop_count_candidate = tab_concurrent[i].hop_count;      
      }
      i++;
    }
    HOP_COUNT = min_hop_count_candidate + 1;
  }
//   printf("my hop_count = %d\r\n", HOP_COUNT);
}
